{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6b405194",
   "metadata": {},
   "source": [
    "---------------------------------\n",
    "* 百度AI实践\n",
    "* 自然语言处理文本信息（实践）\n",
    "* 自然语言生成文本信息（实践）\n",
    "---------------------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "446c864d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"log_id\":1650340839876295909,\"error_msg\":\"invalid parameter(s)\",\"error_code\":282004}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "API_KEY = \"VDvAcG8XnFgfCFdOH7XA4qTh\"\n",
    "SECRET_KEY = \"CBd9gB9dgZswioDorUaGZjQ1k8SPCfVD\"\n",
    "\n",
    "def main():\n",
    "        \n",
    "    url = \"https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=&access_token=\" + get_access_token()\n",
    "    \n",
    "    payload = {\n",
    "        \n",
    "  \"text\": \"百度是一家高科技公司\"\n",
    "}\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Accept': 'application/json'\n",
    "    }\n",
    "    \n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "    \n",
    "    print(response.text)\n",
    "    \n",
    "\n",
    "def get_access_token():\n",
    "    \"\"\"\n",
    "    使用 AK，SK 生成鉴权签名（Access Token）\n",
    "    :return: access_token，或是None(如果错误)\n",
    "    \"\"\"\n",
    "    url = \"https://aip.baidubce.com/oauth/2.0/token\"\n",
    "    params = {\"grant_type\": \"client_credentials\", \"client_id\": API_KEY, \"client_secret\": SECRET_KEY}\n",
    "    return str(requests.post(url, params=params).json().get(\"access_token\"))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "89195a25",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"text\":\"百度是一家高科技公司\",\"items\":[{\"uri\":\"\",\"formal\":\"\",\"ne\":\"ORG\",\"item\":\"百度\",\"loc_details\":[],\"basic_words\":[\"百度\"],\"byte_offset\":0,\"byte_length\":4,\"pos\":\"\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"是\",\"loc_details\":[],\"basic_words\":[\"是\"],\"byte_offset\":4,\"byte_length\":2,\"pos\":\"v\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"一家\",\"loc_details\":[],\"basic_words\":[\"一\",\"家\"],\"byte_offset\":6,\"byte_length\":4,\"pos\":\"\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"高科技\",\"loc_details\":[],\"basic_words\":[\"高\",\"科技\"],\"byte_offset\":10,\"byte_length\":6,\"pos\":\"n\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"ORG\",\"item\":\"公司\",\"loc_details\":[],\"basic_words\":[\"公司\"],\"byte_offset\":16,\"byte_length\":4,\"pos\":\"\"}],\"log_id\":1650341498619556144}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "API_KEY = \"VDvAcG8XnFgfCFdOH7XA4qTh\"\n",
    "SECRET_KEY = \"CBd9gB9dgZswioDorUaGZjQ1k8SPCfVD\"\n",
    "\n",
    "def main():\n",
    "        \n",
    "    url = \"https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8&access_token=\" + get_access_token()\n",
    "    \n",
    "    payload = json.dumps({\n",
    "        \"text\": \"百度是一家高科技公司\"\n",
    "    })\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Accept': 'application/json'\n",
    "    }\n",
    "    \n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "    \n",
    "    print(response.text)\n",
    "    \n",
    "\n",
    "def get_access_token():\n",
    "    \"\"\"\n",
    "    使用 AK，SK 生成鉴权签名（Access Token）\n",
    "    :return: access_token，或是None(如果错误)\n",
    "    \"\"\"\n",
    "    url = \"https://aip.baidubce.com/oauth/2.0/token\"\n",
    "    params = {\"grant_type\": \"client_credentials\", \"client_id\": API_KEY, \"client_secret\": SECRET_KEY}\n",
    "    return str(requests.post(url, params=params).json().get(\"access_token\"))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1c03970",
   "metadata": {},
   "source": [
    "# 语音识别测试-百度API-ASR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3a41cd1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f24ee05c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'audio/16k.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "#     print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#     print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "#         print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "def asr(token,AUDIO_FILE):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "#     print(\"url is\", url);\n",
    "#     print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "#     print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1767bf90",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 语音识别执行如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "251fa22b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.424e8dbb39ff72558e172d687067bf4e.2592000.1689232458.282335-19331335'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c800cde6",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'audio/16k.wav'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Input \u001b[1;32mIn [5]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[43masr\u001b[49m\u001b[43m(\u001b[49m\u001b[43mxu_token\u001b[49m\u001b[43m,\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43maudio/16k.wav\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "Input \u001b[1;32mIn [2]\u001b[0m, in \u001b[0;36masr\u001b[1;34m(token, AUDIO_FILE)\u001b[0m\n\u001b[0;32m     88\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21masr\u001b[39m(token,AUDIO_FILE):\n\u001b[0;32m     89\u001b[0m     speech_data \u001b[38;5;241m=\u001b[39m []\n\u001b[1;32m---> 90\u001b[0m     \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28;43mopen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mAUDIO_FILE\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mrb\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mas\u001b[39;00m speech_file:\n\u001b[0;32m     91\u001b[0m         speech_data \u001b[38;5;241m=\u001b[39m speech_file\u001b[38;5;241m.\u001b[39mread()\n\u001b[0;32m     92\u001b[0m     length \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mlen\u001b[39m(speech_data)\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'audio/16k.wav'"
     ]
    }
   ],
   "source": [
    "asr(xu_token,'audio/16k.wav')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d88550a0",
   "metadata": {},
   "source": [
    "# 语音识别自动回复文本机器人\n",
    "\n",
    "> 1. 准备录制音频文件 （完成）\n",
    "> 2. 调用语音识别，将音频转成文本 （已完成）\n",
    "> 3. 文本自动回复 （已完成）原理: 问和答，I/O 输入和输出----特点： key:value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61676820",
   "metadata": {},
   "source": [
    "## 准备录制音频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c5ad744e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: SpeechRecognition in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (3.10.0)\n",
      "Requirement already satisfied: requests>=2.26.0 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from SpeechRecognition) (2.27.1)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests>=2.26.0->SpeechRecognition) (2.0.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests>=2.26.0->SpeechRecognition) (2021.10.8)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests>=2.26.0->SpeechRecognition) (1.26.9)\n",
      "Requirement already satisfied: idna<4,>=2.5 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests>=2.26.0->SpeechRecognition) (3.3)\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ac22e84b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: PyAudio in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (0.2.13)\n",
      "Collecting pipwin\n",
      "  Downloading pipwin-0.5.2.tar.gz (7.9 kB)\n",
      "Collecting docopt\n",
      "  Downloading docopt-0.6.2.tar.gz (25 kB)\n",
      "Requirement already satisfied: requests in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from pipwin) (2.27.1)\n",
      "Collecting pyprind\n",
      "  Downloading PyPrind-2.11.3-py2.py3-none-any.whl (8.4 kB)\n",
      "Requirement already satisfied: six in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from pipwin) (1.16.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from pipwin) (4.11.1)\n",
      "Collecting js2py\n",
      "  Downloading Js2Py-0.74-py3-none-any.whl (1.0 MB)\n",
      "Requirement already satisfied: packaging in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from pipwin) (21.3)\n",
      "Collecting pySmartDL>=1.3.1\n",
      "  Downloading pySmartDL-1.3.4-py3-none-any.whl (20 kB)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.3.1)\n",
      "Collecting pyjsparser>=2.5.1\n",
      "  Downloading pyjsparser-2.7.1.tar.gz (24 kB)\n",
      "Collecting tzlocal>=1.2\n",
      "  Downloading tzlocal-5.0.1-py3-none-any.whl (20 kB)\n",
      "Collecting tzdata\n",
      "  Downloading tzdata-2023.3-py2.py3-none-any.whl (341 kB)\n",
      "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from packaging->pipwin) (3.0.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.9)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests->pipwin) (2021.10.8)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in d:\\users\\lenovo\\anaconda3\\lib\\site-packages (from requests->pipwin) (3.3)\n",
      "Building wheels for collected packages: pipwin, docopt, pyjsparser\n",
      "  Building wheel for pipwin (setup.py): started\n",
      "  Building wheel for pipwin (setup.py): finished with status 'done'\n",
      "  Created wheel for pipwin: filename=pipwin-0.5.2-py2.py3-none-any.whl size=8790 sha256=61d9fd7ec7845eb603cdf210c91531cd11510dfde9b08e9f038c106e4dff32a5\n",
      "  Stored in directory: c:\\users\\lenovo\\appdata\\local\\pip\\cache\\wheels\\bc\\86\\30\\f70db104d3f51560d9a177d6ced4f7e09f3e474d6985c101ae\n",
      "  Building wheel for docopt (setup.py): started\n",
      "  Building wheel for docopt (setup.py): finished with status 'done'\n",
      "  Created wheel for docopt: filename=docopt-0.6.2-py2.py3-none-any.whl size=13723 sha256=581c05daa29a3545b29e8f8b54e61e9eae547f1a62ca77ef8710427f7809e6f9\n",
      "  Stored in directory: c:\\users\\lenovo\\appdata\\local\\pip\\cache\\wheels\\70\\4a\\46\\1309fc853b8d395e60bafaf1b6df7845bdd82c95fd59dd8d2b\n",
      "  Building wheel for pyjsparser (setup.py): started\n",
      "  Building wheel for pyjsparser (setup.py): finished with status 'done'\n",
      "  Created wheel for pyjsparser: filename=pyjsparser-2.7.1-py3-none-any.whl size=26000 sha256=cc026e2a7d0d0e314cad3e7d3d12200d10367c37d6b6c1d3c11dbab3db6ef739\n",
      "  Stored in directory: c:\\users\\lenovo\\appdata\\local\\pip\\cache\\wheels\\f0\\70\\61\\f42dc45dcf0fbe8c495ce579b04730787081499bfb5b8bc60e\n",
      "Successfully built pipwin docopt pyjsparser\n",
      "Installing collected packages: tzdata, tzlocal, pyjsparser, pySmartDL, pyprind, js2py, docopt, pipwin\n",
      "Successfully installed docopt-0.6.2 js2py-0.74 pipwin-0.5.2 pySmartDL-1.3.4 pyjsparser-2.7.1 pyprind-2.11.3 tzdata-2023.3 tzlocal-5.0.1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Usage:\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\n",
      "  pipwin uninstall <package>\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\n",
      "  pipwin search <package> [--proxy=<proxy>]\n",
      "  pipwin list\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\n",
      "  pipwin (-h | --help)\n",
      "  pipwin (-v | --version)\n"
     ]
    }
   ],
   "source": [
    "!pip install PyAudio\n",
    "\n",
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f8d7e003",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75fc4c5f",
   "metadata": {},
   "source": [
    "## 文本自动回复(自定义)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5fc2c63d",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"你好呀，有什么事么？\",\n",
    "    \"你叫什么名字\":\"我是人见人爱，花见花开的小小度呀\",\n",
    "    \"你多大了\":\"这是很私密的问题，我今年18岁了。\",\n",
    "    \"苹果用英文怎么说\":\"apple\",\n",
    "    \"今天天气\":\"我这边墨迹天气显示，今天广州30度，晴\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ac352814",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好呀，有什么事么？'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get('你好')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "dcc1b774",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'我是人见人爱，花见花开的小小度呀'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get('你叫什么名字')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cecb91d",
   "metadata": {},
   "source": [
    "## 实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2ea08524",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 1.142933\n"
     ]
    }
   ],
   "source": [
    "# 1. 录制音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "# 通过调用电脑的麦克风进行音频的获取\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2. 调用百度asr\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result = eval(asr(xu_token,\"1.wav\"))['result'][0][:-1]  # eval()---> str to dict\n",
    "# asr_result\n",
    "\n",
    "# 3. 文本自动回复\n",
    "qa.get(asr_result)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8117547",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
